<?php

/**
 * Zend_Controller_action, LoginVerwaltung und Registreierung, Startseite
 * @author  Christian Greweling, Sascha Witte
 */
class AccountController extends Zend_Controller_Action {

    protected $account;
    protected $language;

    public function init() {

        $this->_statusMessenger = $this->_helper->flashMessenger;
        $this->_errorMessenger = new Zend_Controller_Action_Helper_FlashMessenger();
        $this->_errorMessenger->setNamespace('error');
        $this->view->statusMessages = $this->_statusMessenger->getMessages();
        $this->view->errorMessages = $this->_errorMessenger->getMessages();


        $locale = new Zend_Locale();
        if ($locale->getLanguage() == 'de') {
            $this->language = 'name_de';
        } else {
            $this->language = 'name_en';
        }
    }

    public function indexAction() {
        
    }

    /**
     * Eingabemaske Login
     * leitet weiter nach checkLoginAction
     * 
     */
    public function loginAction() {

        $this->view->headTitle(_('Login'));
        $this->view->documentClasses = array('account', 'login');

        $this->view->form = $this->_getLoginForm();
    }

    /**
     * Uberprueft Eingabedaten Benutzer Passwort
     * Setzt ZendAuth
     * leitet weiter nach /event
     * 
     */
    public function checkLoginAction() {
        // Zurueck zu index, falls kein POST-Request
        // hereinkommt
        if (!$this->_request->isPost()) {
            $this->_errorMessenger->addMessage($this->view->translate('Use the loginform to log in.'));
            return $this->_helper->redirector('index');
        }

        $form = $this->_getLoginForm();

        // falls das Formular falsch ausgefuellt ist, zurueck!
        if (!$form->isValid($this->_request->getPost())) {
            $this->view->form = $form;
            return $this->render('login');
        }

        $authAdapter = new Zend_Auth_Adapter_DbTable(
                        Zend_Db_Table::getDefaultAdapter(),
                        'user',
                        'username',
                        'password'
        );
        $params = $form->getValues();
        $authAdapter->setIdentity($params['username'])
                ->setCredential(md5($params['password']));
        $auth = Zend_Auth::getInstance();
        $authValid = $auth->authenticate($authAdapter)->isValid();


        if (!$authValid) {
            $this->view->form = $form;
            $this->_errorMessenger->addMessage($this->view->translate('Incorrect login data.'));
            return $this->_helper->redirector('login');
        }
        if ($authValid) {
            //Angemeldeten Benutzer speichern 
            $usertemp = $authAdapter->getResultRowObject();
            $auth->getStorage()->write($usertemp);
            $this->_statusMessenger->addMessage($this->view->translate('You are logged in.'));
            $this->_redirect('event');
        }
    }

    /**
     * Ausloggen 
     * leitet weiter nach /index
     * 
     */
    public function logoutAction() {
        Zend_Auth::getInstance()->clearIdentity();
        //$refererUrl = $this->_request->getServer('HTTP_REFERER');
        $this->_statusMessenger->addMessage($this->view->translate('You are logged out.'));
        $this->_redirect('index');
    }

    /**
     * Update der Nutzerdaten  
     */
    public function updateAction() {


        $this->view->headTitle($this->view->translate('Update your Account'));

        // Javascript das die gewaehlte Spielerfarbe gleich in die UI uebertraegt.

        $this->view->headScript()->appendScript('

          $(document).ready(function() {
            $("#color-element input:radio").click(function() {
                $("#status li").first().css("color", "#"+$(this).val());
            });
          });
          ');
        $form = $this->_getUpdateAccountForm();
        $this->view->form = $form;

        $usermapper = new Application_Model_UserMapper();
        $userId = Zend_Auth::getInstance()->getIdentity()->id;
        $userModel = $usermapper->find(($userId), new Application_Model_UserModel);
        //passwort löschen
        //  $userModel->setPassword('');
        $form->setDefaults($userModel->toArray());

        $this->saveAccount($userId);
    }

    /**
     * Passwort aendern
     * leitet weiter zu /index 
     */
    public function passwordAction() {


        $this->view->headTitle($this->view->translate('Change your Password'));

        // Javascript das die gewaehlte Spielerfarbe gleich in die UI uebertraegt.


        $form = $this->_getUpdatePasswordForm();
        $this->view->form = $form;



        $post = $this->_request->getPost();

        if ($post) {
            if (!$this->view->form->isValid($post)) {
                $this->view->form->populate($post);
            }

            $values = $this->view->form->getValues();
            $userId = Zend_Auth::getInstance()->getIdentity()->id;
            //$values['id'] = (int) $userId;
            $usermapper = new Application_Model_UserMapper();


            $userModel = $usermapper->find(($userId), new Application_Model_UserModel);

            if ($userModel->getPassword() != md5($values['oldpassword'])) {
                // Fehler
                $this->view->form->oldpassword->addError($this->view->translate('old password incorrect.'));
                $this->view->form->populate($post);
            } else if ($post['password'] != $post['password_repeat']) {
                $this->view->form->password_repeat->addError($this->view->translate('the passwords are not the same.'));
                $this->view->form->populate($post);
            } else {

                $userModel->setPassword(md5($values['password']));


                $userModel->getMapper()->save($userModel);


                $this->_statusMessenger->addMessage(
                        $this->view->translate('password changed.')
                );
                $this->_redirect('index');
            }
        }
    }

    /**
     * Eingabemaske Registrierung
     * leitet weiter nach checkLoginAction
     * 
     */
    public function registerAction() {

        $this->view->headTitle($this->view->translate('Create your Account'));
        $this->view->form = $this->_getRegisterForm();
        $this->saveAccount($userId = NULL);
        /*
          if ($this->getRequest()->isPost()) {

          if ($form->isValid($this->_request->getPost())) {
          try {

          $newAccount = new Application_Model_UserModel();
          $newAccount->setEmail($values[email]);
          $newAccount->setSalutation($values[salutation]);
          $newAccount->setConfirm($this->genRandomString(32));

          $mail = new Zend_Mail();
          $mail->setFrom(Zend_Registry::get('config')->email->adress, Zend_Registry::get('config')->email->from);
          $mail->addTo($newAccount->getEmail(), "{$newAccount->getSalutation() }");
          $mail->setSubject('Dear ' . $newAccount->getSalutation() . ' confirm your account');

          $mail->setBodyText('Dear' . $newAccount->getSalutation() . ',
          Your scoring account has been created!
          To complete registration, click on the link to confirm your e-mail address.
          http://scoring/account/confirm/key/{$newaccount["recovery"]}

          Once confirmed, you\'ll be able to login.
          Have fun, scoring!');
          $mail->send();

          $this->saveAccount($userId = NULL);
          } catch (Exception $e) {
          $this->_errorMessenger->addMessage($this->view->translate('Error while sending eMail!'));
          }
          }
          }
         */
    }

    /**
     * speichert Account für registerAction und UpdateAction
     * leitet weiter zu /index
     * @param type $userId 
     */
    protected function saveAccount($userId) {
        $post = $this->_request->getPost();

        if ($post) {
            if (!$this->view->form->isValid($post)) {
                $this->view->form->populate($post);
            } elseif ($post['password'] != $post['password_repeat']) {
                $this->view->form->password_repeat->addError($this->view->translate('the passwords are not the same.'));
                $this->view->form->populate($post);
            } else {
                // verarbeite Daten
                $values = $this->view->form->getValues();
                if ($userId == NULL) {
                    $values['confirm'] = $this->genRandomString(32);
                    $values['password'] = md5($values['password']);
                }
                //falls $userid Update
                if ($userId != NULL) {
                    $values['id'] = (int) $userId;
                    $usermapper = new Application_Model_UserMapper();
                    $userModel = $usermapper->find(($userId), new Application_Model_UserModel);
                    $values['password'] = $userModel->getPassword();
// Um ein neues Passwort zu setzen muss das alte Passwort dem der Datenbank entsprechen
                }

      // Um Namen und neue Spielerfarbe gleich und nicht erst bei erneutem Einloggen zu sehen 
                $authData = Zend_Auth::getInstance()->getIdentity();
                $authUser = new stdClass();

                foreach ($authData as $key => $value) {
                    $authUser->$key = $value;
                }
                $authUser->color = $values['color'];
                $authUser->salutation = $values['salutation'];

                Zend_Auth::getInstance()->getStorage()->write($authUser);
            }
            $user = new Application_Model_UserModel($values);
            $user->getMapper()->save($user);

            if (null !== $user->id) {
                $this->_statusMessenger->addMessage(
                        $this->view->translate('Update complete.')
                );
            } else {
                $this->_errorMessenger->addMessage(
                        $this->view->translate('Error while updating!')
                );
            }

            $this->_redirect('index');
        }
    }

    /**
     * Erstellt Login Formular
     * 
     *  @return $form Zend_Form Login
     */
    protected function _getLoginForm() {
        $form = new Zend_Form();
        $form->setAction('/account/check-login')
                ->setMethod(Zend_Form::METHOD_POST)
                ->addElements(array(
                    array('text', 'username', array(
                            'required' => true,
                            'label' => _('Username')
                    )),
                    array('password', 'password', array(
                            'required' => true,
                            'label' => _('Password')
                    )),
                    array('hidden', 'referer', array(
                            'decorators' => array('ViewHelper'),
                            'value' => $this->_request->getServer('HTTP_REFERER')
                    )),
                    array('submit', 'submit', array(
                            'label' => _('Login')
                    ))
                ));
        $this->translatePlaceholder($form);
        return $form;
    }

    /**
     * Erstellt Registrierungs Formular
     * 
     * Weiterleitung nach /index
     * 
     *  @return $form Zend_Form Registierung
     */
    protected function _getRegisterForm() {
        $form = new Zend_Form();


        $table = new Application_Model_ColorMapper();
        $table = $table->fetchFree();

        $colorSelect = new Zend_Form_Element_Radio('color');
        $colorSelect->setLabel(_('Choose color'));

// TODO: sehr hässlich
        $number = 0 + Zend_Auth::getInstance()->getIdentity()->id;
        $db = Zend_Db_Table::getDefaultAdapter();
        $select = new Zend_Db_Select($db);
        $select->from('color', array('id', 'hex', 'name_en', 'name_de'))
                ->joinLeft('user', 'color.hex = user.color', array())
                ->where('user.color IS NULL')
                ->orWhere('user.id = ?', $number);
        $resultSet = $db->fetchAll($select);

        foreach ($resultSet as $c) {
            $colorSelect->addMultiOption($c['hex'], $c[$this->language]);
        }

        $form->setMethod(Zend_Form::METHOD_POST);
        $form->addElements(array(
            array('text', 'salutation', array(
                    'label' => _('Name'),
                    'size' => '32',
                    'placeholder' => _('What should we call you?')
            )),
            array('radio', 'gender', array(
                    'label' => _('Gender'),
                    'size' => '32',
                    // 'decorators'=> array('ViewHelper'), 
                    'multiOptions' => array(
                        m => _('male'),
                        f => _('female'),
                    ),
                    'separator' => ' '
            )),
        ));

        $form->addElement($colorSelect);
        $form->addElements(array(
            array('text', 'username', array(
                    'label' => _('Username'),
                    'placeholder' => _('Your login name'),
                    'size' => '32',
                    'required' => true,
                    'validators' => array(
                        array('regex', false, '/^[a-zA-Z0-9_]+$/'),
                        array('StringLength', false, 4)
                    )
            ))
        ));
        $form->addElements(array(
            array('password', 'password', array(
                    'label' => _('Password'),
                    'placeholder' => _('password123'),
                    'size' => '32',
                    'required' => true,
                    'validators' => array(
                        array('StringLength', false, 8) // aendern!
                    )
            )),
            array('password', 'password_repeat', array(
                    'label' => _('Repeat Password'),
                    'placeholder' => _('password123'),
                    'size' => '32',
                    'required' => true
            )),
            array('text', 'email', array(
                    'label' => _('E-Mail-Adress'),
                    'placeholder' => _('your@mail.com'),
                    'size' => '32',
                    'required' => true,
                    'validators' => array(
                        'EmailAddress'
                    )
            )),
            array('submit', 'submit', array(
                    'label' => _('Save'),
                    'decorators' => array('ViewHelper')
            ))
        ));
        $form->getElement('email')->addValidator('Db_NoRecordExists', false, array(
            'table' => 'user',
            'field' => 'email',
            'messages' => array(Zend_Validate_Db_NoRecordExists::ERROR_RECORD_FOUND => _('Address allready used'))
        ));
        $form->getElement('email')->addValidator('Db_NoRecordExists', false, array(
            'table' => 'user',
            'field' => 'email',
            'messages' => array(Zend_Validate_Db_NoRecordExists::ERROR_RECORD_FOUND => _('Address allready used'))
        ));

        $form->getElement('username')->addValidator('Db_NoRecordExists', false, array(
            'table' => 'user',
            'field' => 'username',
            'messages' => array(Zend_Validate_Db_NoRecordExists::ERROR_RECORD_FOUND => _('Usersame allready used'))
        ));
        $this->translatePlaceholder($form);
        return $form;
    }

    protected function _getUpdateAccountForm() {
        $form = new Zend_Form();


        $table = new Application_Model_ColorMapper();
        $table = $table->fetchFree();

        $colorSelect = new Zend_Form_Element_Radio('color');
        $colorSelect->setLabel(_('Choose color'));

// TODO: sehr hässlich
        $number = 0 + Zend_Auth::getInstance()->getIdentity()->id;
        $db = Zend_Db_Table::getDefaultAdapter();
        $select = new Zend_Db_Select($db);
        $select->from('color', array('id', 'hex', 'name_en', 'name_de'))
                ->joinLeft('user', 'color.hex = user.color', array())
                ->where('user.color IS NULL')
                ->orWhere('user.id = ?', $number);
        $resultSet = $db->fetchAll($select);

        foreach ($resultSet as $c) {
            $colorSelect->addMultiOption($c['hex'], $c[$this->language]);
        }

        $form->setMethod(Zend_Form::METHOD_POST);
        $form->addElements(array(
            array('text', 'salutation', array(
                    'label' => _('Name'),
                    'size' => '32',
                    'placeholder' => _('What should we call you?')
            )),
            array('radio', 'gender', array(
                    'label' => _('Gender'),
                    'size' => '32',
                    // 'decorators'=> array('ViewHelper'), 
                    'multiOptions' => array(
                        m => _('male'),
                        f => _('female'),
                    ),
                    'separator' => ' '
            )),
        ));

        $form->addElement($colorSelect);
        $form->addElements(array(
            array('text', 'username', array(
                    'label' => _('Username'),
                    'placeholder' => _('Your login name'),
                    'size' => '32',
                    'validators' => array(
                        array('regex', false, '/^[a-zA-Z0-9_]+$/'),
                        array('StringLength', false, 4)
                    )
            )),
            array('text', 'email', array(
                    'label' => _('E-Mail-Adress'),
                    'placeholder' => _('your@mail.com'),
                    'size' => '32',
                    'required' => true,
                    'validators' => array(
                        'EmailAddress'
                    )
            )),
            array('submit', 'submit', array(
                    'label' => _('Save'),
                    'decorators' => array('ViewHelper')
            ))
        ));
        $emailValue = Zend_Auth::getInstance()->getIdentity()->email;
        $userValue = Zend_Auth::getInstance()->getIdentity()->username;

        $form->getElement('email')->addValidator('Db_NoRecordExists', false, array(
            'table' => 'user',
            'field' => 'email',
            'exclude' => array(
                'field' => 'email',
                'value' => $emailValue),
            'messages' => array(Zend_Validate_Db_NoRecordExists::ERROR_RECORD_FOUND => _('Address allready used'))
        ));

        $form->getElement('username')->addValidator('Db_NoRecordExists', false, array(
            'table' => 'user',
            'field' => 'username',
            'exclude' => array(
                'field' => 'username',
                'value' => $userValue),
            'messages' => array(Zend_Validate_Db_NoRecordExists::ERROR_RECORD_FOUND => _('Usersame allready used'))
        ));

        $this->translatePlaceholder($form);
        return $form;
    }

    protected function _getUpdatePasswordForm() {
        $form = new Zend_Form();
        $form->setMethod(Zend_Form::METHOD_POST)
                ->addElements(array(
                    array('password', 'oldpassword', array(
                            'label' => _('Old Password'),
                            'placeholder' => _('your previous password'),
                            'size' => '32',
                            'required' => true,
                            'validators' => array(
                                array('StringLength', false, 8) // aendern!
                            )
                    )),
                    array('password', 'password', array(
                            'label' => _('New Password'),
                            'placeholder' => _('password123'),
                            'size' => '32',
                            'required' => true,
                            'validators' => array(
                                array('StringLength', false, 8) // aendern!
                            )
                    )),
                    array('password', 'password_repeat', array(
                            'label' => _('Repeat new Password'),
                            'required' => true,
                            'placeholder' => _('to be sure, once again'),
                            'size' => '32'
                    )),
                    array('submit', 'submit', array(
                            'label' => _('Save'),
                            'decorators' => array('ViewHelper')
                    ))
                ));
        $this->translatePlaceholder($form);
        return $form;
    }

    /**
     * Erstellt ZufallsString laenge =12
     * 
     *  @param $length laenge = 12
     * 
     *  @return $tring Zufallsstring
     */
    public function genRandomString($length = 12) {
        $characters = "0123456789abcdefghijklmnopqrstuvwxyz";
        $string = "";
        for ($p = 0; $p < $length; $p++) {
            $string .= $characters[mt_rand(0, strlen($characters) - 1)];
        }
        return $string;
    }

    /**
     * Übersetzt die placeholder in der From 
     * @param type $form ZendFrom 
     */
    private function translatePlaceholder($form) {
        foreach ($form->getElements() as $key => $element) {
            $placeholder = $element->getAttrib('placeholder');
            if (isset($placeholder)) {
                $form->$key->setAttrib('placeholder', $this->view->translate($placeholder));
            }
        }
    }

}

